//
//  WJCommonWetherUtil.m
//  imfei
//
//  Created by 王军 on 2017/12/6.
//  Copyright © 2017年 jun.wang. All rights reserved.
//
/***
 拉取天气信息的工具使用方法
 1.强制刷新天气（app启动时）
 2.获取当前天气，允许缓存
 ***/

#import "WJCommonWeatherUtil.h"
#import "WJLocationManager.h"
#import "WJSimpleNetwork.h"
#import "WJCommonUtils.h"
#import "NSDictionary+MutableDeepCopy.h"
#import "WJCommonUtils+cache.h"

@implementation WJCommonWeatherUtil

+(WJCommonWeatherUtil *)shareInstance{
    static WJCommonWeatherUtil *r_rootInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        r_rootInstance = [[WJCommonWeatherUtil alloc] init];
        [r_rootInstance initOptions];
        [r_rootInstance initData];
    });
    return r_rootInstance;
}

- (void)initOptions{
    self.cacheTime = 2 * 3600;// 默认2小时
}

- (void)initData{
    
}

- (void)getWeatherOption:(NSInteger)option callback:(void (^)(id result))callback{
    [[WJLocationManager shareInstance] fetchLocationInfoSuccess:^(id result) {
        NSString *city = [WJCommonUtils obj2str:result[@"City"]];
        if (![WJCommonUtils isBlankString:city]) {
            NSTimeInterval nowtime = [[NSDate date] timeIntervalSince1970];
            if (self.lastRequestTime > 0  && nowtime - self.lastRequestTime < 3) {
                callback(@"已经请求中");
                return;
            }
            self.lastRequestTime = nowtime;
            [self getWeather:city option:option callback:callback];
            return;
        }
        [self if_location_fail_callback:callback];
    } fail:^(id result) {
        [self if_location_fail_callback:callback];
    }];
}

-(void)if_location_fail_callback:(void (^)(id result))callback{
    [self getWeatherByIP_callback:callback];
}

- (void)getWeatherByIP_callback:(void (^)(id result))callback{
    NSString *urlStr = [NSString stringWithFormat:@"http://app.gshyj.com/api/weather/v2"];
    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlStr];
    [WJSimpleNetwork getMethodContent:url success:^(NSString *content) {
        if ([content isKindOfClass:[NSString class]]) {
            NSDictionary *ret =  [WJCommonUtils JSONParse:content];
            if ([ret isKindOfClass:[NSDictionary class]]) {
                if ([ret[@"code"] integerValue] == 1) {
                    self.weatherInfo = [ret mutableDeepCopy];
                    callback(ret);
                    return;
                }
            }
        }
        callback(@"失败");
    } fail:^(NSString *message) {
        NSLog(@"%@", message);
        callback(@"失败");
    }];
}

// option 1使用缓存 2不使用缓存
- (void)getWeather:(NSString *)city option:(NSInteger)option callback:(void (^)(id result))callback{
    if (option == 1) { //使用缓存
        NSDictionary *lastWeather = [WJCommonUtils getWJCache:[NSString stringWithFormat:@"kLastWeather_%@",city]];
        if ([lastWeather isKindOfClass:[NSDictionary class]]) {
            NSString *lastTimeStampStr = lastWeather[@"lastTimeStamp"];
            NSTimeInterval lastTimeStamp = lastTimeStampStr.integerValue;
            NSTimeInterval nowtime = [[NSDate date] timeIntervalSince1970];
            if (nowtime - lastTimeStamp < self.cacheTime) {
                NSDictionary *lastWeatherData = lastWeather[@"lastWeatherData"];
                self.weatherInfo = [lastWeatherData mutableDeepCopy];
                callback(lastWeatherData);
                return;
            }
        }
    }
    // 用city 去查询
    NSString *urlStr = [NSString stringWithFormat:@"http://app.gshyj.com/api/weather/v2?city=%@",city];
    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url =  [NSURL URLWithString:urlStr];
    [WJSimpleNetwork getMethodContent:url success:^(NSString *content) {
        if ([content isKindOfClass:[NSString class]]) {
            NSDictionary *ret =  [WJCommonUtils JSONParse:content];
            if ([ret isKindOfClass:[NSDictionary class]]) {
                if ([ret[@"code"] integerValue] == 1) {
                    self.weatherInfo = [ret mutableDeepCopy];
                    NSTimeInterval nowtime = [[NSDate date] timeIntervalSince1970];
                    NSString *nowtimeStr = [NSString stringWithFormat:@"%f",nowtime];
                    NSMutableDictionary *saveData = [NSMutableDictionary new];
                    saveData[@"lastCity"] = city;
                    saveData[@"lastTimeStamp"] = nowtimeStr;
                    saveData[@"lastWeatherData"] = self.weatherInfo;
                    [WJCommonUtils saveWJCache:saveData withKey:@"kLastWeather"];
                    [WJCommonUtils saveWJCache:saveData withKey:[NSString stringWithFormat:@"kLastWeather_%@",city]];
                    callback(ret);
                    return;
                }
            }
        }
        callback(@"失败");
    } fail:^(NSString *message) {
        NSLog(@"%@", message);
        callback(@"失败");
    }];
}

/** 获取室外温度 */
+(NSString *)getOutsideTemp {
    NSDictionary *weatherInfo = [WJCommonWeatherUtil shareInstance].weatherInfo;
    if ([weatherInfo isKindOfClass:[NSDictionary class]]) {
        NSString *tmp = [WJCommonUtils obj2str:weatherInfo[@"tmp"]];
        return tmp;
    }
    return @"";
}

@end
